from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import translate  # 假设translate.py和本脚本在同一目录
import base64

def decrypt_with_webcrypto(data: bytes, password: str) -> str:
    salt = data[:16]
    iv = data[16:28]
    ciphertext = data[28:]
    kdf = PBKDF2HMAC(
        algorithm=hashes.SHA256(),
        length=32,
        salt=salt,
        iterations=100000,
    )
    key = kdf.derive(password.encode('utf-8'))
    aesgcm = AESGCM(key)
    plain = aesgcm.decrypt(iv, ciphertext, None)
    return plain.decode('utf-8')

if __name__ == '__main__':
    # 1. 读取加密文件
    with open(r'json路径', 'rb') as f:
        data = f.read()
    encoded_str = "ZmoyNjIxNDQu"
    decoded_bytes = base64.b64decode(encoded_str)
    password = decoded_bytes.decode('utf-8')
    # 2. 解密
    json_string = decrypt_with_webcrypto(data, password)
    #输出解密后的文档
    # print(json_string)
    # 3. 直接调用translate.py的函数
    cookies_dict = translate.extract_cookies_from_json_string(json_string)
    if not cookies_dict:
        print("❌ 没有找到目标 Cookie，请确认 JSON 格式正确且包含目标字段。")
    else:
        translate.save_cookies_to_ini(cookies_dict)